package com.huyn.baseframework.statesync;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by huyn on 2015/6/3.
 */
public abstract class BaseAsyncHelper<T> {

    public static final int STATE_DELAY_TIME = 1000;

    protected HashMap<String, T> objMaps;

    protected Context context;

    protected Handler mHandler;

    protected INetworkRequestBridge iNetworkRequestBridge;

    protected List<IDataObserver> mDataObservers;

    protected BaseAsyncHelper(Context context, INetworkRequestBridge bridge) {
        objMaps = new HashMap<>();
        this.context = context;
        this.iNetworkRequestBridge = bridge;
        mHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message obj) {
                if(objMaps.containsKey(obj.what + "")) {
                    doRequest(objMaps.get(obj.what + ""));
                }
                return false;
            }
        });
    }

    public void clearCache() {
        if(objMaps == null)
            objMaps = new HashMap<>();
        else
            objMaps.clear();
    }

    public int size() {
        return (objMaps != null) ? objMaps.size() : 0;
    }

    public boolean isEmpty() {
        return objMaps == null || objMaps.isEmpty();
    }

    protected abstract void doRequest(T t);

    public void registObserver(IDataObserver observer) {
        if(mDataObservers == null)
            mDataObservers = new ArrayList<>();
        if(observer == null)
            return;
        if(mDataObservers.contains(observer))
            return;
        mDataObservers.add(observer);
    }

    public void unregistObserver(IDataObserver observer) {
        if(mDataObservers == null)
            return;
        mDataObservers.remove(observer);
    }

    public void notifyDataChanged() {
        if(mDataObservers == null)
            return;
        for(IDataObserver observer : mDataObservers)
            observer.stateUpdate();
    }

}
